﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using Tools.Model;
using Tools.Utils;

namespace Tools.Service
{
    public class PdfService
    {
        /// <summary>
        /// pdf转图片
        /// </summary>
        /// <param name="path">pdf路径</param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public int PdfToImages(string path,string savePath)
        {
            PdfHelper pdfHelper = new PdfHelper();
            pdfHelper.ConvertAllPDF2Images(path, $"{savePath}\\", "{0}", System.Drawing.Imaging.ImageFormat.Jpeg, PdfHelper.Definition.Two);

            var zipPath = $"{savePath}.zip";
            new CompressHelper().CompressDirectory(savePath, zipPath, 9, false);

            return new DirectoryInfo(savePath).GetFiles().Length;
        }

        /// <summary>
        /// pdf添加水印
        /// </summary>
        /// <param name="savePath">pdf保存路径</param>
        /// <param name="oldPath">pdf路径</param>
        /// <param name="watermarkPath">水印图片路径</param>
        /// <param name="waterMarkName">水印文字</param>
        /// <param name="type">类型（img-图片,text-文字）</param>
        /// <param name="number">水印数量（one-一个，covered-铺满）</param>
        /// <param name="location">水印位置(top-内容上面，bottom-内容下面)</param>
        /// <param name="rotation">旋转角度</param>
        /// <param name="layout">布局（1-左上方，2顶部中间，3-右上方，4-左边，5-中间，6-右边，7-左下方，8-底部中间，9-右下方）</param>
        /// <returns></returns>
        public ExcutedResult PdfWaterMark(string savePath, string oldPath, string watermarkPath,string waterMarkName, string type, string number, string location, string rotation, string layout)
        {
            PdfHelper pdfHelper = new PdfHelper();
            ExcutedResult excutedResult = new ExcutedResult();

            if (type == "img")
            {
                excutedResult= pdfHelper.AddImageWatermarkPDF(oldPath, savePath, watermarkPath, number, location, rotation, layout);
            }
            else
            {
                excutedResult = pdfHelper.AddWordWatermark2PDF(oldPath, savePath, waterMarkName, number, location, rotation, layout);
            }

            return excutedResult;
        }

        /// <summary>
        /// 合并文件
        /// </summary>
        /// <param name="files">需要合并文件路径</param>
        /// <param name="saveFilePath">保存文件路径</param>
        public void MergePDFFiles(List<string> files, string saveFilePath)
        {
            FileStream fs = null;
            Document document = null;
            string newFileName = "";
            try
            {
                //如果文件存在先删除
                DeleteFile(saveFilePath);
                PdfReader reader = null;
                document = new Document();
                fs = new FileStream(saveFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                PdfWriter writer = PdfWriter.GetInstance(document, fs);
                document.Open();
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage newPage;
                files.ForEach(x =>
                {
                    newFileName = x;
                    if (System.IO.File.Exists(x))
                    {
                        reader = new PdfReader(x);
                        PdfReader.unethicalreading = true;
                        int iPageNum = reader.NumberOfPages;
                        for (int j = 1; j <= iPageNum; j++)
                        {
                            var oldRect = reader.GetPageSize(j);
                            if (oldRect.Height < oldRect.Width)
                            {
                                SetPageSizeHen(document);
                            }
                            else
                            {
                                SetPageSizeShu(document);
                            }
                            document.NewPage();
                            newPage = writer.GetImportedPage(reader, j);
                            newPage.Rectangle(oldRect);
                            cb.AddTemplate(newPage, 0f, 0f);
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                //LogUtil.Error("合并PDF异常：" + newFileName + ex.ToString());
                //return ExcutedResult.Failure(message: $"合并PDF异常：" + ex.Message);
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                    document.Dispose();
                }
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }

        /// <summary>
        /// 删除文件 有可能存在权限不够，暂时不做处理
        /// </summary>
        /// <param name="path">文件路径</param>
        public void DeleteFile(string filePath)
        {
            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }
            }
            catch (Exception ex) { throw ex; }
        }

        /// <summary>
        /// 设置页面横向
        /// </summary>
        /// <param name="document"></param>
        public void SetPageSizeHen(Document document)
        {
            //横向
            Rectangle pageSize = new Rectangle(PageSize.A4.Height, PageSize.A4.Width);
            pageSize.Rotate();
            document.SetPageSize(pageSize);
        }

        /// <summary>
        /// 设置页面竖向
        /// </summary>
        /// <param name="document"></param>
        public void SetPageSizeShu(Document document)
        {
            //竖向
            Rectangle pageSize = new Rectangle(PageSize.A4.Width, PageSize.A4.Height);
            pageSize.Rotate();
            document.SetPageSize(pageSize);
        }
    }
}
